﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TaskDemo
{

    class Program
    {
        /// <summary>
        ///做事 需要 ms秒 才能完成
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        static async Task<string> Doing(int time, string name = "JobDefault")
        {
            Console.WriteLine(name + " begin");
            await Task.Delay(TimeSpan.FromMilliseconds(time));
            return string.Format("Job {1} use：{0} ms ", time, name);
        }

        /// <summary>
        /// 设定超时任务  如果超时返回
        /// </summary>
        /// <param name="needTimeOut"></param>
        /// <returns></returns>
        static async Task<string> TimeOut(int job_ms)
        {
            
            var begin = DateTime.Now;
            var timeOutTask = Task.Delay(150);//1.设定一个超时的任务
            var doing = Doing(job_ms);//2. 真正需要执行的任务
            var task = await Task.WhenAny(doing, timeOutTask);//返回任何一个完成的任务
            if (task == timeOutTask)//如果超时任务先完成了  就返回timeout！
            {
                //Console.WriteLine("timeout");
                return "timeout";
            }
            var end = DateTime.Now;
            Console.WriteLine("use：" + (end - begin).Milliseconds + " ms");
            return await doing;
        }

        /// <summary>
        /// 多任务一起执行
        /// </summary>
        /// <returns></returns>
        static async Task Tasks()
        {
            var begin = DateTime.Now;
            var list = new List<string>();
            var t1 = Doing(1000, "a");//1.定义任务
            var t2 = Doing(1500, "b");
            var t3 = Doing(1200, "c");
            var tasks = new[] { t1, t2, t3 };//2.任务组

            var process = tasks.Select(async tt =>//3.等待任务结束  并保存值
            {
                var result = await tt;
                list.Add(result);
            });
            await Task.WhenAll(process);//4.等待处理完全
            foreach (var i in list)//5.查看结果
            {
                Console.WriteLine(i);
            }
            var end = DateTime.Now;
            Console.WriteLine("use：" + (end - begin).Milliseconds+" ms");


        }

        static void Main(string[] args)
        {
            Tasks();
            //Task<string> res = TimeOut(160);
            //Console.WriteLine(res.Result);
            Console.ReadKey();
        }
    }
}
